﻿using System;
using System.Collections.Generic;
using Gumini.JulaDB.DataTypes;
using Gumini.JulaDB.Expressions.Functions;

namespace Gumini.JulaDB.Expressions
{
    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    internal class AggregateFunctionCall : Expression
    {
        private readonly AggregateFunction _function;

        public AggregateFunctionCall(AggregateFunction function, Expression child)
            : base(child)
        {
            _function = function;
        }

        public Expression Child
        {
            get { return _children[0]; }
        }

        public override TypedValue Evaluate(List<Context<TypedValue>> contexts)
        {
            var values = new List<TypedValue>();
            foreach (var context in contexts)
                values.Add(Child.Evaluate(context));
            object result = _function.Evaluate(values);
            return new TypedValue(_function.GetReturnType(), result);
        }

        public override DataType InferType(Context<DataType> context)
        {
            Child.InferType(context);
            return _function.GetReturnType();
        }

        protected override bool IsAggregateCore
        {
            get { return true; }
        }

        public override bool Equals(Expression other)
        {
            var b = other as AggregateFunctionCall;
            if (b == null)
                return false;
            return
                this._function.Equals(b._function) &&
                this.Child.Equals(b.Child);
        }

        public override string ToString()
        {
            return String.Format("{0}({1})", _function.Name, Child.ToString());
        }
    }
}
